package com.javabasic.net.netty.client;

import org.jboss.netty.bootstrap.ClientBootstrap;
import org.jboss.netty.channel.*;
import org.jboss.netty.channel.socket.nio.NioClientSocketChannelFactory;
import org.jboss.netty.handler.codec.string.StringDecoder;
import org.jboss.netty.handler.codec.string.StringEncoder;

import java.net.InetSocketAddress;
import java.util.Scanner;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @Author xiongmin
 * @Description //TODO
 * @Date 2019/12/12 21:59
 * @Version 1.0
 **/
public class HelloClient {

    private static Scanner cin = new Scanner(System.in);

    public static void main(String[] args) {

        // 服务类
        ClientBootstrap clientBootstrap = new ClientBootstrap();

        // 线程池
        ExecutorService boss = Executors.newCachedThreadPool();
        ExecutorService worker = Executors.newCachedThreadPool();

        // 设置socket工厂
        clientBootstrap.setFactory(new NioClientSocketChannelFactory(boss, worker));

        // 设置管道工厂
        clientBootstrap.setPipelineFactory(new ChannelPipelineFactory() {
            @Override
            public ChannelPipeline getPipeline() throws Exception {
                ChannelPipeline pipeline = Channels.pipeline();
                pipeline.addLast("decode", new StringDecoder());
                pipeline.addLast("encode", new StringEncoder());
                pipeline.addLast("helloHandler", new HelloClientHandler());
                return pipeline;
            }
        });

        // 连接服务端，这个过程事异步的
        ChannelFuture channelFuture = clientBootstrap.connect(new InetSocketAddress("localhost", 9000));
        Channel channel = channelFuture.getChannel();

        while (true) {
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("向服务端写数据：");
            String next = cin.nextLine();
            channel.write(next);
        }
    }
}
